package com.woniu.controller.mallSystem;

import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.woniu.model.gh.common.Result;
import com.woniu.model.mallSystem.entity.China;
import com.woniu.model.mallSystem.gh.common.RedisConstant;
import com.woniu.service.mallSystem.IAddressService;
import com.woniu.service.mallSystem.IChinaService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * <p>
 * 地址表 前端控制器
 */
@RestController
@RequestMapping("/address")
public class AddressController {

    @Autowired
    private IAddressService addressService;
    @Autowired
    private IChinaService chinaService;
    @Autowired
    private RedisTemplate redisTemplate;




    /**
     * 查询所有省份
     */
    @GetMapping("/getAllProvinces")
    public Result getAllProvinces(){

        List<China> provincesList = null;
        //Redis是否缓存有省份key
        if (!redisTemplate.hasKey(RedisConstant.PROVINCES)) {
            //查询省份： SELECT * FROM t_china WHERE id!=0 and pid=0
            provincesList = chinaService.list(Wrappers.lambdaQuery(China.class).ne(China::getId, 0)
                    .eq(China::getPid, 0));
            //存到Redis的set集合
            provincesList.forEach(china -> {
                redisTemplate.opsForSet().add(RedisConstant.PROVINCES, JSONUtil.toJsonStr(china));
            });
        } else {
            //从redis取出来
            Set<String> datas = redisTemplate.opsForSet().members(RedisConstant.PROVINCES);
            provincesList = datas.stream().map(str -> {
                //str 就是China对象的JSON字符串,字符串转换对象收集
                China china = JSONUtil.toBean(str, China.class);
                return china;
            }).collect(Collectors.toList());
        }
        return Result.ok(provincesList);
    }
    /**
     * 根据省份查询所有的城市
     */
    @GetMapping("/getAllCities")
    public Result getAllCities(Integer provinceId) {
        List<China> citiesList = chinaService.getAllCities(provinceId);
        return Result.ok(citiesList);
    }
    /**
     * 根据城市加载区域
     */
    @GetMapping("/getAllCounties")
    public Result getAllCounties(Integer cityId) {
        List<China> countiesList = chinaService.getAllCounties(cityId);
        return Result.ok(countiesList);
    }
}
